#!/bin/bash
# vim: set ft=sh

set -e

<%
  require "shellwords"

  def esc(x)
    Shellwords.shellescape(x)
  end
%>

RUN_DIR=/var/vcap/sys/run/baggageclaim
LOG_DIR=/var/vcap/sys/log/baggageclaim
BIN_DIR="$(cd $(dirname $0) && pwd)"
PIDFILE=$RUN_DIR/baggageclaim.pid

source /var/vcap/packages/pid_utils/pid_utils.sh

case $1 in

  start)
    pid_guard $PIDFILE "baggageclaim"

    mkdir -p $RUN_DIR
    chown -R vcap:vcap $RUN_DIR

    mkdir -p $LOG_DIR
    chown -R vcap:vcap $LOG_DIR

    IMAGE_PATH=/var/vcap/data/baggageclaim/volumes.img
  <% if p('volumes_image_size_mb') > 0 %>
    IMAGE_SIZE=<%= p('volumes_image_size_mb') %>
  <% else %>
    DISK_SIZE=$(df -m /var/vcap/data | tail -n1 | awk '{print $2}')
    IMAGE_SIZE=$(($DISK_SIZE - 10 * 1024))

    if [[ $IMAGE_SIZE -lt 0 ]]; then
      IMAGE_SIZE=$DISK_SIZE
    fi
  <% end %>
    mkdir -p $(dirname ${IMAGE_PATH})

    VOLUMES_DIR=/var/vcap/data/baggageclaim/volumes
    mkdir -p ${VOLUMES_DIR}

    # break out of bosh-lite device limitations
    chmod +x "${BIN_DIR}/permit_device_control"
    unshare -m "${BIN_DIR}/permit_device_control" $$

    for i in $(seq 0 64); do
      if ! mknod -m 0660 /dev/loop$i b 7 $i; then
        break
      fi
    done

    /var/vcap/packages/baggageclaim/bin/fs_mounter \
      --disk-image ${IMAGE_PATH} \
      --mount-path ${VOLUMES_DIR} \
      --size-in-megabytes ${IMAGE_SIZE} \
      --mkfs-bin /var/vcap/packages/btrfs_tools/sbin/mkfs.btrfs \
      1>>$LOG_DIR/fs_mounter.stdout.log \
      2>>$LOG_DIR/fs_mounter.stderr.log

    echo $$ > $PIDFILE

    exec /var/vcap/packages/baggageclaim/bin/baggageclaim \
      --volumes ${VOLUMES_DIR} \
      --driver btrfs \
      --bind-ip <%= p("bind_ip") %> \
      --bind-port <%= p("bind_port") %> \
      --yeller-api-key <%= esc(p("yeller.api_key")) %> \
      --yeller-environment <%= esc(p("yeller.environment_name")) %> \
      --btrfs-bin /var/vcap/packages/btrfs_tools/sbin/btrfs \
      --mkfs-bin /var/vcap/packages/btrfs_tools/sbin/mkfs.btrfs \
      1>>$LOG_DIR/baggageclaim.stdout.log \
      2>>$LOG_DIR/baggageclaim.stderr.log

    ;;

  stop)
    kill_and_wait $PIDFILE

    ;;

  *)
    echo "Usage: $0 {start|stop}"

    ;;

esac
